package com.sz.app.oss.api.logistics.base;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.constants.CommCodes;
import com.sz.biz.logistics.base.entity.Port;
import com.sz.biz.logistics.base.service.PortService;
import com.sz.biz.logistics.base.dto.PortDto;
import com.sz.common.base.dto.I18nDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.service.I18nBaseService;
import com.sz.common.base.utils.EntityUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.system.entity.SysDict;
import com.sz.common.core.system.service.SysDictService;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Function: PortController <br>
 * Author: penghui.zheng <br>
 * Date: 2017-5-17 15:19:00
 */
@RestController
@RequestMapping("/api/v1/biz/port")
@Api(description = " ", tags = "042、港口管理")
public class PortController extends BaseController {
    //Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private PortService portService;
    @Autowired
    private SysDictService dictService;
    @Autowired
    private I18nBaseService i18nService;
    @Value("${i18n.biz.port}")
    private String i18nTable;


    @ApiOperation(value = "获取港口类型列表", notes = "返回港口类型列表")
    @RequestMapping(value = "", method = {RequestMethod.GET})
    public
    @ResponseBody
    ResultDto getPortTypes() throws BizException {
        List<SysDict> dictList = dictService.findByCatalog(CommCodes.SYS_DICT_BIZ_PORT_TYPE);
        ResultDto dto = new ResultDto();
        dto.setData(dictList);
        return dto;
    }

    /**
     * 分页查询港口
     *
     * @throws Exception
     */
    @ApiOperation(value = "搜索港口", notes = "搜索港口<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "countryId", value = "国家必填项，这样才能区分到后台去查地区那张表", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "cityId", value = "城市", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小，max2000", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue = "true")})
    @RequestMapping(value = "/searchlist", method = {RequestMethod.GET})
    public
    @ResponseBody
    ResultDto findPortList(@RequestParam(required = false) String countryId,
                           @RequestParam(required = false) String cityId, @RequestParam(required = false) String q,
                           @RequestParam int pageIndex, @RequestParam int pageSize, @RequestParam(required = false) String sort,
                           @RequestParam(required = false, defaultValue = "true") Boolean asc) {
        q = StringUtils.replaceSqlPattern(q);
        Map<String, Object> map = new HashMap<>();
        map.put("countryId", countryId);
        map.put("cityId", cityId);
        ResultDto dto = portService.findPortList(new QueryParams(pageSize, pageIndex, q, sort, asc).put(map));
        return dto;
    }
    /**
     * 查询港口短接口
     *
     * @throws Exception
     */
    @ApiOperation(value = "搜索港口短接口", notes = "搜索港口<br>权限：" )
    @ApiImplicitParams({
    	    @ApiImplicitParam(name = "countryId", value = "国家必填项，这样才能区分到后台去查地区那张表", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "cityId", value = "城市", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小，max2000", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue = "true")})
    @RequestMapping(value = "/searchlist/short", method = {RequestMethod.GET})
    public
    @ResponseBody
    ResultDto findShortList(@RequestParam(required = false) String countryId,
                           @RequestParam(required = false) String cityId, 
                           @RequestParam(required = false) String q,
                           @RequestParam int pageIndex, 
                           @RequestParam int pageSize, 
                           @RequestParam(required = false) String sort,
                           @RequestParam(required = false, defaultValue = "true") Boolean asc) {
        q = StringUtils.replaceSqlPattern(q);
        Map<String, Object> map = new HashMap<>();
        map.put("countryId", countryId);
        map.put("cityId", cityId);
        ResultDto dto = portService.findPortShortList(new QueryParams(pageSize, pageIndex, q, sort, asc).put(map));
        return dto;
    }

    /**
     * 新建一个港口
     *
     * @throws Exception
     */
    @ApiOperation(value = "新建港口", notes = "新建港口<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @RequestMapping(value = "", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_STATION_PORT)
    public ResultDto savePort(@RequestBody PortDto portDto) {
        Port port = new Port();
        portDto.setId(null);// 保存时忽略id
        EntityUtils.copyPropertiesIgnoreNull(portDto, port);
        int id = portService.savePort(portDto);
        i18nService.save(id, portDto.getI18n(), i18nTable);
        ResultDto result = this.getSaveSuccessDto(MessagesCodes.MODULE_PORT);
        result.setData(id);
        return result;
    }

    /**
     * 修改港口
     *
     * @throws Exception
     */
    @ApiOperation(value = "修改港口", notes = "修改港口<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @RequestMapping(value = "/{id}", method = {RequestMethod.PUT})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_STATION_PORT)
    public
    @ResponseBody
    ResultDto updatePort(@PathVariable int id, @RequestBody PortDto portDto) {
        portDto.setId(id);
        portService.updatePort(portDto);
        i18nService.save(id, portDto.getI18n(), i18nTable);
        ResultDto dto = this.getUpdateSuccessDto(MessagesCodes.MODULE_PORT);
        dto.setData(id);
        return dto;
    }

    /**
     * 根据id删除港口 ,逻辑删除
     *
     * @throws Exception
     */
    @ApiOperation(value = "删除港口", notes = "删除港口<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "List", paramType = "body")})
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_STATION_PORT)
    public
    @ResponseBody
    ResultDto deletePort(@RequestBody List<Integer> ids) {
        portService.deleteByPortIds(ids);
        return getDeleteSuccessDto(MessagesCodes.MODULE_PORT);
    }

    /**
     * 根据国家二字码查询城市
     *
     * @throws Exception
     */
    @ApiOperation(value = "查询城市", notes = "查询城市<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "countryId", value = "国家", dataType = "string", paramType = "query")})
    @RequestMapping(value = "/city/{countryId}", method = {RequestMethod.GET})
    public ResultDto getCityByCountryCode(@RequestParam(required = false) String countryId) {
        return  portService.findCityByCountryCode(countryId);
    }
    /**
     * 根据港口id查询港口
     *
     * @throws Exception
     */
    @ApiOperation(value = "查询港口", notes = "查询港口<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "港口的id ", required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public ResultDto getPortById(@PathVariable int id) {
        PortDto portDto = portService.findByPortId(id);
        ResultDto dto = new ResultDto();
        dto.setData(portDto);
        return dto;
    }
    /**
     * 根据港口id查询港口短接口
     *
     * @throws Exception
     */
    @ApiOperation(value = "查询港口短接口", notes = "查询港口短接口<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "港口的id ", required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "short/{id}", method = {RequestMethod.GET})
    public ResultDto findShortById(@PathVariable int id) {
        Port port = portService.findShortById(id);
        ResultDto dto = new ResultDto();
        dto.setData(port);
        return dto;
    }
    /**
     * 根据条件获取国际化数据集合
     *
     * @param language  语言信息
     * @param q         参数信息
     * @param pageIndex 哪页
     * @param pageSize  分页大小
     * @param sort      排序字段的名称
     * @param asc       true asc false desc
     * @return 查询的国际化数据集合
     * @throws Exception 异常信息
     */
    @ApiOperation(value = "查询i18n", notes = "根据指定条件获取国际化数据集合<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言信息", dataType = "string", paramType = "path", required = true),
            @ApiImplicitParam(name = "unfilled", value = "未填写项", dataType = "Boolean", paramType = "query"),
            @ApiImplicitParam(name = "q", value = "模糊查询参数", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query")}

    )
    @RequestMapping(value = "i18n/list/{language}", method = RequestMethod.GET)
    public ResultDto findI18n(@PathVariable String language, @RequestParam(required = false) String q,
                              @RequestParam(required = true) Boolean unfilled,
                              @RequestParam(required = false, defaultValue = "1") int pageIndex,
                              @RequestParam(required = false, defaultValue = "10") int pageSize,
                              @RequestParam(required = false) String sort,
                              @RequestParam(required = false, defaultValue = "true") Boolean asc) {
        q = StringUtils.replaceSqlPattern(q);
        Map<String, Object> map = new HashMap<>();
        map.put("unfilled", unfilled);
        ResultDto dto = portService.findI18nByParam(new QueryParams(pageSize, pageIndex, q, sort, asc, language).put(map));
        return dto;
    }

    /**
     * 批量新增或修改国际化.
     *
     * @param dtos 要保存或修改的国际化实体集合
     * @return 处理成功与否的返回信息
     */
    @ApiOperation(value = "新增或修改i18n", notes = "批量新增或修改港口国际化<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @RequestMapping(value = "i18n", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_STATION_PORT)
    public ResultDto saveI18n(@RequestBody @ApiParam(value = "要保存的对象集合", required = true) List<I18nDto> dtos) {
        i18nService.save(dtos, i18nTable);
        if(dtos!=null){
        	for(I18nDto dto:dtos){
        		Port port=new Port();
        		port.setId((Integer)dto.getRefId());
        		port.setEnglishName(dto.getLocalName());
        		portService.synchroPort(port);
        	}
        }
        
        return getSaveI18nSuccessDto();
    }

    /**
     * 异步校验港口编码
     */
    @ApiOperation(value = "异步校验港口编码", notes = "异步校验港口编码<br>权限：" + Permissions.BIZ_MGT_BASE_STATION_PORT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "港口编码", required = true, dataType = "string", paramType = "query")})
    @RequestMapping(value = "/checkcode", method = {RequestMethod.GET})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_STATION_PORT)
    public
    @ResponseBody
    ResultDto codeCheck(@RequestParam(required = false, defaultValue = "0") int id, @RequestParam(required = true) String code) {
        portService.checkCode(code, id);
        return new ResultDto();
    }
}
